﻿using System;
using System.Data;
using System.Configuration;
using Gizmox.WebGUI.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Xml;
using System.ComponentModel;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using BUS;
using System.Text.RegularExpressions;

namespace TVC
{
    public class clsConfigurarion
    {
        public static string ServerDirPath;
        static XmlDocument _xmlLocalization;
        static Dictionary<string, string> _distionary = new Dictionary<string, string>();
        BindingList<clsControlsInForm> _controlsInForm = new BindingList<clsControlsInForm>();
        public BindingList<clsControlsInForm> ControlsInForm
        {
            get { return _controlsInForm; }
            set { _controlsInForm = value; }
        }

        public Dictionary<string, string> Distionary
        {
            get { return _distionary; }
            set { _distionary = value; }
        }
        public static Dictionary<string, string> GetSecurDictionary(string strXML, string itemName, string key, string value)
        {
            if (_distionary.Count == 0)
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(strXML);

                XmlElement xmlDoc = xml.DocumentElement;
                foreach (XmlElement xmlEle in xmlDoc.ChildNodes)
                {
                    if (xmlEle.Name == itemName)
                    {
                        string akey = string.Empty;
                        string avalue = string.Empty;
                        foreach (XmlElement ele in xmlEle.ChildNodes)
                        {
                            if (ele.Name == key && akey == string.Empty)
                                akey = ele.InnerText;
                            if (ele.Name == value && akey == string.Empty)
                                avalue = ele.InnerText;
                        }
                        _distionary.Add(akey, avalue);
                    }
                }
            }
            return _distionary;
        }
        public void GetControlsInForm(string formCode, string keyLanguage)
        {
            XmlTextReader reader = null;

            try
            {
                // System.Resources.ResourceManager.
                //    StringReader stream = new StringReader(System.Convert.ToString(Properties.Resources.ResourceManager.GetObject(origin))); // if table = ICAS - load from origin CA
                // StringReader stream = new StringReader(Reporting.Proper
                reader = new XmlTextReader(formCode);
                string id = string.Empty;
                string type = string.Empty;
                string index = "";
                string languageCode = "";

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element & reader.Name == "ITEM")
                    {
                        id = reader.GetAttribute("ID");
                        type = reader.GetAttribute("Type");
                        index = reader.GetAttribute("Index");

                        languageCode = reader.GetAttribute(keyLanguage);
                        clsControlsInForm control = new clsControlsInForm(id, type, index, languageCode);
                        _controlsInForm.Add(control);
                    }
                }

            }
            catch (Exception )
            {
                //   throw new ArgumentException("Alias Dictionary Building problem " + ex.Message);
            }
            finally
            {
                if (!(reader == null))
                {
                    reader.Close();
                }

            }
        }
        public clsConfigurarion()
        {


        }

        public string GetValueDictionary(string key)
        {
            if (_distionary.ContainsKey(key))
            {

                return _distionary[key];
            }
            else
            {
                return key;
            }
        }
        public static void SetLanguage(Control page, string fileConfig, string languageCode)
        {
            if (languageCode != "")
            {
                clsConfigurarion config = new clsConfigurarion();
                config.GetControlsInForm(String.Format("{0}/Configuration/Form/{1}", ServerDirPath, fileConfig), languageCode);
                //page.Title = config.GetValueDictionary(title);
                //ContentPlaceHolder content = (ContentPlaceHolder)tmp.Master.FindControl("ContentPlaceHolder2");
                //Control x = content;
                SetLanguage(config, ref page);
            }
        }
        public static string SetLanguage(string page, string fileConfig, string languageCode)
        {
            if (languageCode != "")
            {
                clsConfigurarion config = new clsConfigurarion();
                config.GetControlsInForm(String.Format("{0}/Configuration/Form/{1}", ServerDirPath, fileConfig), languageCode);
                //page.Title = config.GetValueDictionary(title);
                //ContentPlaceHolder content = (ContentPlaceHolder)tmp.Master.FindControl("ContentPlaceHolder2");
                //Control x = content;
                SetLanguage(config, ref page);
            }
            return page;
        }
        public static string GetErrMsg(string key, string languageCode)
        {
            if (languageCode != "")
            {
                 clsConfigurarion config = new clsConfigurarion();
                return config.GetMsgCode(key, String.Format("{0}/Configuration/ErroCodes.xml", ServerDirPath), languageCode);
                //page.Title = config.GetValueDictionary(title);
                //ContentPlaceHolder content = (ContentPlaceHolder)tmp.Master.FindControl("ContentPlaceHolder2");
                //Control x = content;
            }
            return "";
        }
        public static string GetAlias(string key)
        {
            clsConfigurarion config = new clsConfigurarion();
            return config.GetAliasCode(key, String.Format("{0}/Configuration/Alias.xml", ServerDirPath));
        }

        private string GetAliasCode(string key, string formCode)
        {
            XmlTextReader reader = null;
            string result = "";
            try
            {
                // System.Resources.ResourceManager.
                //    StringReader stream = new StringReader(System.Convert.ToString(Properties.Resources.ResourceManager.GetObject(origin))); // if table = ICAS - load from origin CA
                // StringReader stream = new StringReader(Reporting.Proper
                reader = new XmlTextReader(formCode);
                string code = string.Empty;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element & reader.Name == "ITEM")
                    {
                        code = reader.GetAttribute("Code");
                        if (key == code)
                            result = reader.GetAttribute("Alias");
                    }
                }
            }
            catch (Exception ex)
            {
                //   throw new ArgumentException("Alias Dictionary Building problem " + ex.Message);return "";
            }
            finally
            {
                if (!(reader == null))
                {
                    reader.Close();
                }

            }
            return result;
        }

        private string GetMsgCode(string key, string formCode, string languageCode)
        {
            XmlTextReader reader = null;
            string result = "";
            try
            {
                // System.Resources.ResourceManager.
                //    StringReader stream = new StringReader(System.Convert.ToString(Properties.Resources.ResourceManager.GetObject(origin))); // if table = ICAS - load from origin CA
                // StringReader stream = new StringReader(Reporting.Proper
                reader = new XmlTextReader(formCode);
                string code = string.Empty;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element & reader.Name == "ITEM")
                    {
                        code = reader.GetAttribute("Code");
                        if (code == key)
                            result = reader.GetAttribute(languageCode);
                    }
                }
            }
            catch (Exception ex)
            {
                //   throw new ArgumentException("Alias Dictionary Building problem " + ex.Message);return "";
            }
            finally
            {
                if (!(reader == null))
                {
                    reader.Close();
                }

            }
            return result;
        }

        public static int ConvertDatetimeToInt(DateTime time)
        {
            String chuoi = time.Year.ToString() + time.Month.ToString("0#.#") + time.Day.ToString("0#.#");
            int rs = Convert.ToInt32(chuoi);
            return rs;
        }
        public static int ConvertTimeToInt(DateTime time)
        {
            String chuoi = time.Hour.ToString("0#.#") + time.Minute.ToString("0#.#");
            int rs = Convert.ToInt32(chuoi);
            return rs;
        }

        public static DateTime ConvertIntToDatetime(int time) // 20011000
        {
            DateTime dt = new DateTime();
            if (time == 0)
            {
                return dt;
            }
            int y = time / 10000;
            int m = (time % 10000) / 100;
            int d = (time % 10000) % 100;
            return new DateTime(y, m, d);
        }
        public static DateTime ConvertBothIntToDatetime(int date, int time) // 123020
        {
            DateTime dt = new DateTime();
            if (date == 0)
            {
                return dt;
            }
            int y = date / 10000;
            int m = (date % 10000) / 100;
            int d = (date % 10000) % 100;
            int h = time / 100;
            int mm = (time % 100);
            int s = (time % 100) % 100;
            return new DateTime(y, m, d, h, mm, s);
        }

        private static void SetLanguage(clsConfigurarion config, ref string content)
        {
            //page.Title = config.GetValueDictionary(title);


            foreach (clsControlsInForm x in config.ControlsInForm)
            {
                string id = x.Id;

                string key = String.Format("<#{0}>", id);
                content = content.Replace(key, x.Description);
            }
            //RadGrid1.Rebind();
            //RadGrid2.Rebind();
        }

        private static void SetLanguage(clsConfigurarion config, ref Control content)
        {
            //page.Title = config.GetValueDictionary(title);


            foreach (clsControlsInForm x in config.ControlsInForm)
            {
                string id = x.Id;

                Control[] arrtmp = content.Controls.Find(id, true);
                if (arrtmp != null)
                {
                    Control tmp = arrtmp[0];
                    switch (x.Type)
                    {
                        case "Label":
                            Label tmpLabel = (Label)tmp;
                            tmpLabel.Text = x.Description;
                            break;
                        //case "RadTabStrip":
                        //    RadTabStrip tmpRadTabStrip = (RadTabStrip)tmp;
                        //    tmpRadTabStrip.Tabs[int.Parse(x.Index)].Text = x.Description;

                        //    break;
                        //case "RadGrid":
                        //    RadGrid tmpRadGrid = (RadGrid)tmp;
                        //    tmpRadGrid.Columns[int.Parse(x.Index)].HeaderText = x.Description;
                        //    break;
                        //case "Button":
                        //    Button tmpButton = (Button)tmp;
                        //    tmpButton.Text = x.Description;
                        //    break;
                        //case "ImageButton":
                        //    ImageButton tmpImageButton = (ImageButton)tmp;
                        //    tmpImageButton.ToolTip = x.Description;
                        //    break;
                        //case "RadSlidingPane":
                        //    RadSlidingPane tmpRadSlidingPane = (RadSlidingPane)tmp;
                        //    tmpRadSlidingPane.Title = x.Description;
                        //    break;
                        //case "HtmlInputButton":
                        //    HtmlInputButton tmpHtmlInputButton = (HtmlInputButton)tmp;
                        //    tmpHtmlInputButton.Value = x.Description;
                        //    break;
                        //case "RadButton":
                        //    RadButton tmpRadButton = (RadButton)tmp;
                        //    tmpRadButton.Text = x.Description;
                        //    break;
                    }
                }
            }
            //RadGrid1.Rebind();
            //RadGrid2.Rebind();
        }

        public static Image resizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (Image)b;
        }

        public static String Format_Number(Decimal temp, string dtb)
        {
            // lay tu database
            String kq = "";
            string sErr = "";

            DBAControl dba_ctr = new DBAControl();
            DTO.DBAInfo dba_info = dba_ctr.Get(dtb, ref sErr);

            string dec = dba_info.DECIMAL_SEPERATOR;
            string thou = dba_info.THOUSAND_SEPERATOR;
            string fm = thou + dec;
            //   string chuoi = new string('0',Convert.ToInt32(dba_info.DECIMAL_PLACES_SUNBUSINESS));
            string num_dec = "N" + dba_info.DECIMAL_PLACES_SUNBUSINESS;
            switch (fm)
            {
                case ".,":
                    System.Globalization.CultureInfo a = new System.Globalization.CultureInfo("de-DE");
                    kq = temp.ToString(num_dec, a);
                    break;
                case ",.":
                    System.Globalization.CultureInfo b = new System.Globalization.CultureInfo("en-US");
                    kq = temp.ToString(num_dec, b);
                    break;
            }

            return kq;
        }

        public static Decimal Format_StringToNumber(string temp, string dtb)
        {
            // lay tu database Regex.Matches(\d 
            Decimal kq = 0;
            if (Regex.IsMatch(temp, @"\d+"))
            {


                string sErr = "";

                DBAControl dba_ctr = new DBAControl();
                DTO.DBAInfo dba_info = dba_ctr.Get(dtb, ref sErr);

                string dec = dba_info.DECIMAL_SEPERATOR;
                string thou = dba_info.THOUSAND_SEPERATOR;
                string fm = thou + dec;
                //   string chuoi = new string('0',Convert.ToInt32(dba_info.DECIMAL_PLACES_SUNBUSINESS));
                //      string num_dec = "N" + dba_info.DECIMAL_PLACES_SUNBUSINESS;
                switch (fm)
                {
                    case ".,":
                        System.Globalization.CultureInfo a = new System.Globalization.CultureInfo("de-DE");
                        kq = Convert.ToDecimal(temp, a);
                        break;
                    case ",.":
                        System.Globalization.CultureInfo b = new System.Globalization.CultureInfo("en-US");
                        kq = Convert.ToDecimal(temp, b);
                        break;
                }
            }
            return kq;
        }

        public static void GetLabel(string aModule, Control aControl, string language)
        {
            string text = "";
            if (_xmlLocalization == null)
                InitLocalization();
            string query = string.Format("//{0}[@id='{1}']", aModule, aControl.Name); // or "//book[@id='{0}']"
            XmlElement ele = (XmlElement)_xmlLocalization.SelectSingleNode(query);
            if (ele == null)
            {
                //ele = _xmlLocalization.CreateElement(aModule);
                //ele.SetAttribute("id", aControl.Name);
                //_xmlLocalization.DocumentElement.AppendChild(ele);
                //ele.SetAttribute(String.Format("_{0}", language), aControl.Text);
                //_xmlLocalization.Save(ServerDirPath + "/Configuration/Localization.xml");
            }
            else
            {
                text = ele.GetAttribute(language);
            }
            if (text != null && text != "")
                aControl.Text = text;
        }
        public static string GetLabel(string aModule, string aControl, string value, string language)
        {
            string text = "";
            if (aModule != null && aModule != "")
            {
                if (_xmlLocalization == null)
                    InitLocalization();
                string query = string.Format("//{0}[@id='{1}']", aModule, aControl); // or "//book[@id='{0}']"
                XmlElement ele = (XmlElement)_xmlLocalization.SelectSingleNode(query);
                if (ele == null)
                {
                    //ele = _xmlLocalization.CreateElement(aModule);
                    //ele.SetAttribute("id", aControl);
                    //_xmlLocalization.DocumentElement.AppendChild(ele);
                    //ele.SetAttribute(String.Format("_{0}", language), value);
                    //_xmlLocalization.Save(ServerDirPath + "/Configuration/Localization.xml");
                }
                else
                {
                    text = ele.GetAttribute(language);
                }
            }
            if (text == null || text == "")
                return value;
            return text;
        }

        public static void SetLabel(string aModule, string controlName, string controlValue, string language)
        {
            if (aModule != null && aModule != "")
            {
                if (_xmlLocalization == null)
                    InitLocalization();
                string query = string.Format("//{0}[@id='{1}']", aModule, controlName); // or "//book[@id='{0}']"
                XmlElement ele = (XmlElement)_xmlLocalization.SelectSingleNode(query);

                //XmlElement ele = _xmlLocalization.SelectSingleNode(String.Format("{0}.{1}", aModule, aControl));
                if (ele == null)
                {
                    ele = _xmlLocalization.CreateElement(aModule);
                    ele.SetAttribute("id", controlName);
                    _xmlLocalization.DocumentElement.AppendChild(ele);
                }
                ele.SetAttribute(language, controlValue);
                _xmlLocalization.Save(String.Format("{0}/Configuration/Localization.xml", ServerDirPath));
            }
        }
        public static void SetLabel(string aModule, Control aControl, string language)
        {
            if (_xmlLocalization == null)
                InitLocalization();
            string query = string.Format("//{0}[@id='{1}']", aModule, aControl.Name); // or "//book[@id='{0}']"
            XmlElement ele = (XmlElement)_xmlLocalization.SelectSingleNode(query);

            //XmlElement ele = _xmlLocalization.SelectSingleNode(String.Format("{0}.{1}", aModule, aControl));
            if (ele == null)
            {
                ele = _xmlLocalization.CreateElement(aModule);
                ele.SetAttribute("id", aControl.Name);
                _xmlLocalization.DocumentElement.AppendChild(ele);
            }
            ele.SetAttribute(language, aControl.Text);
            _xmlLocalization.Save(String.Format("{0}/Configuration/Localization.xml", ServerDirPath));
        }
        static void InitLocalization()
        {
            _xmlLocalization = new XmlDocument();
            _xmlLocalization.Load(String.Format("{0}/Configuration/Localization.xml", ServerDirPath));
        }
    }
}
